package com.net.oil.main.fragment;


import android.content.Intent;
import android.os.Bundle;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.net.oil.R;
import com.net.oil.action.ActionDetailActivity;
import com.net.oil.app.Constant;
import com.net.oil.app.UserInfoManager;
import com.net.oil.base.BaseFragment;
import com.net.oil.base.EventBussMessage;
import com.net.oil.car.MyCarDetailActivity;
import com.net.oil.http.AppUrl;
import com.net.oil.main.FeedbackActivity;
import com.net.oil.main.adapter.BannerViewPagerAdapter;
import com.net.oil.main.adapter.ProductRecyclerViewAdapter;
import com.net.oil.main.bean.HomePageInfoBean;
import com.net.oil.main.contract.HomePageContract;
import com.net.oil.main.presenter.HomePagePresenter;
import com.net.oil.message.MessageActivity;
import com.net.oil.user.LoginActivity;
import com.net.oil.user.bean.UserInfo;
import com.net.oil.util.DisplayUtil;
import com.net.oil.util.SharedPreferencesKey;
import com.net.oil.util.SharedPreferencesUtil;
import com.net.oil.util.StringUtil;
import com.net.oil.util.WebViewUtil;
import com.net.oil.util.glide.GlideUtil;
import com.net.oil.widget.BannerViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * 首页fragment
 */
public class HomePageFragment extends BaseFragment<HomePagePresenter> implements HomePageContract.View {

    @BindView(R.id.toolbar_go_back)
    ImageView toolbarGoBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.main_banner)
    BannerViewPager mainBanner;
    @BindView(R.id.banner_dot_group)
    RadioGroup bannerDotGroup;
    Unbinder unbinder;
    @BindView(R.id.product_recycler_view)
    RecyclerView productRecyclerView;
    @BindView(R.id.web_view)
    WebView webView;
    @BindView(R.id.phone_number_tv)
    TextView phoneNumberTv;
    @BindView(R.id.car_name)
    TextView carName;
    @BindView(R.id.car_detail_tv)
    TextView carDetailTv;
    @BindView(R.id.car_layout)
    RelativeLayout carLayout;
    @BindView(R.id.hint_tv)
    TextView hintTv;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.user_head_portrait)
    ImageView userHeadPortrait;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.banner_layout)
    RelativeLayout bannerLayout;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    private ProductRecyclerViewAdapter adapter;
    private Gson gson = new Gson();

    private static String mimeType = "text/html; charset=UTF-8";
    //    private static String encoding = "UTF-8";
    private WebSettings webSetting;

    private UserInfo userInfo;
    private UserInfo.UserDetailBean userDetail;

    private HomePageInfoBean homePageInfoBean;

    public HomePageFragment() {
    }

    public static HomePageFragment newInstance() {
        return new HomePageFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        unbinder = ButterKnife.bind(this, view);
        presenter = new HomePagePresenter(this);
        EventBus.getDefault().register(this);
        initView();
        initDataFromCache();
        return view;
    }

    private void initDataFromCache() {
        //从保存的数据中取出banner数据初始化
        String bannerJson = SharedPreferencesUtil.getStringParam(getContext(), SharedPreferencesKey.BANNER_DATA, "");
        if (!StringUtil.isEmpty(bannerJson)) {
            List<HomePageInfoBean.LoopList> bannerList = gson.fromJson(bannerJson, new TypeToken<List<HomePageInfoBean.LoopList>>() {
            }.getType());
            setBannerView(bannerList);
        }

    }

    private void initData() {
        presenter.getHomePageInfo();
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    private void initView() {

        initUserInfo();

        toolbarGoBack.setVisibility(View.GONE);
        toolbarTitle.setText(getText(R.string.home_page));

        adapter = new ProductRecyclerViewAdapter(getContext());
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
        productRecyclerView.setNestedScrollingEnabled(false);
        productRecyclerView.setLayoutManager(layoutManager);
        productRecyclerView.setAdapter(adapter);

        webSetting = webView.getSettings();
        webSetting.setTextZoom(100);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setUseWideViewPort(true);  //将图片调整到适合webview的大小
        webSetting.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        int screenWidth = DisplayUtil.getScreenWidth();
        params.width = screenWidth;
        params.height = (int) (screenWidth / 2.3);
        mainBanner.setLayoutParams(params);

        mainBanner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                bannerDotGroup.check(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });

        toolbar.inflateMenu(R.menu.main_menu);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_message:
                        startActivity(new Intent(getContext(), MessageActivity.class));
                        break;
                    case R.id.menu_car:
                        startActivity(new Intent(getContext(), MyCarDetailActivity.class));
                        break;
                    case R.id.menu_feedback:
                        startActivity(new Intent(getContext(), FeedbackActivity.class));
                        break;
                }
                return true;
            }
        });

    }

//    @Override
//    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//        getActivity().getMenuInflater().inflate(R.menu.main_menu, menu);
//        super.onCreateOptionsMenu(menu, inflater);
//    }

    private void setBannerView(List<HomePageInfoBean.LoopList> list) {

        mainBanner.removeAllViews();
        bannerDotGroup.removeAllViews();

        if (list.size() > 0) {
            bannerLayout.setVisibility(View.VISIBLE);
            RadioGroup.LayoutParams buttonParams = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            buttonParams.setMargins(DisplayUtil.dip2px(5), 0,
                    DisplayUtil.dip2px(5), 0);

            List<ImageView> imageViews = new ArrayList<>();

            for (int i = 0; i < list.size(); i++) {

                final HomePageInfoBean.LoopList loopList = list.get(i);

                ImageView imageView = new ImageView(getContext());
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//            imageView.setImageResource(R.mipmap.main_bg);
                if (!StringUtil.isEmpty(loopList.getImage())) {
                    GlideUtil.getInstance().loadImage(getContext(), imageView, AppUrl.getImageUrl(loopList.getImage()), R.drawable.banner_err);
                }
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(HomePageFragment.this.getContext(), ActionDetailActivity.class);
                        intent.putExtra(Constant.INTENT_ACTION_KEY, loopList.getId());
                        startActivity(intent);
                    }
                });
                imageViews.add(imageView);
                //动态生成RadioButton,设置button属性
                RadioButton button = new RadioButton(getContext());
                button.setButtonDrawable(null);
                button.setLayoutParams(buttonParams);
                button.setWidth(DisplayUtil.dip2px(6));
                button.setHeight(DisplayUtil.dip2px(6));
                button.setId(i);
                button.setBackgroundResource(R.drawable.banner_dot_bg_selector);
                if (i == 0) {
                    button.setChecked(true);
                }
                bannerDotGroup.addView(button);

                //如果只有一条轮播数据，则隐藏圆点
                if (i < 1) {
                    if (bannerDotGroup.getVisibility() == View.VISIBLE) {
                        bannerDotGroup.setVisibility(View.GONE);
                    }
                } else {
                    if (bannerDotGroup.getVisibility() == View.GONE) {
                        bannerDotGroup.setVisibility(View.VISIBLE);
                    }
                }
            }

            BannerViewPagerAdapter bannerViewPagerAdapter = new BannerViewPagerAdapter(imageViews);
            mainBanner.setAdapter(bannerViewPagerAdapter);
            mainBanner.setCurrentItem(0);
            mainBanner.setOffscreenPageLimit(imageViews.size());
            mainBanner.start();
        } else {
            bannerLayout.setVisibility(View.GONE);
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && isAdded()) {
            initUserInfo();
        }
    }

    private void initUserInfo() {
        userInfo = UserInfoManager.getInstance().getUserInfo();
        if (userInfo != null) {
            userDetail = userInfo.getUserDetail();
        }
    }

    /**
     * 接受eventBus消息
     *
     * @param message 消息
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void receiveEventBus(EventBussMessage message) {

        //接受登录或者退出的消息
        if (message.getCode() == Constant.LOGIN_SUCCESS_CODE || message.getCode() == Constant.LOGOUT_CODE) {
            presenter.getHomePageInfo();
            userInfo = UserInfoManager.getInstance().getUserInfo();
            if (userInfo != null) {
                userDetail = userInfo.getUserDetail();
            }
            setCarLayoutView();
        }

        //更新头像
        if (message.getCode() == Constant.UPLOAD_USER_HEAD_SUCCESS_CODE) {
            if (!StringUtil.isEmpty(userDetail.getPortrait())) {
                GlideUtil.getInstance().loadCircleImage(getContext(), userHeadPortrait, AppUrl.getImageUrl(userDetail.getPortrait()),
                        R.drawable.ic_user_default);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mainBanner.stop();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    private void setCarLayoutView() {
        if (UserInfoManager.getInstance().isLogin()) {
            if (homePageInfoBean != null) {
                hintTv.setVisibility(View.GONE);
                carLayout.setVisibility(View.VISIBLE);
                HomePageInfoBean.MycarBean myCar = homePageInfoBean.getMycar();
                if (myCar != null) {
                    if (userDetail != null) {
                        if (!StringUtil.isEmpty(userDetail.getPhone())) {
                            phoneNumberTv.setText(userDetail.getPhone());
                        }

                        if (!StringUtil.isEmpty(userDetail.getPortrait())) {
                            GlideUtil.getInstance().loadCircleImage(getContext(), userHeadPortrait, AppUrl.getImageUrl(userDetail.getPortrait()),
                                    R.drawable.ic_user_default);
                        }
                    }
                    if (myCar.getCarModelInfo() != null) {
                        HomePageInfoBean.MycarBean.CarModelInfoBean carInfo = myCar.getCarModelInfo();
                        if (!StringUtil.isEmpty(carInfo.getBrand())) {
                            carName.setText(carInfo.getBrand());
                        }
                        if (!TextUtils.isEmpty(carInfo.getEngine())) {
                            content.setText(carInfo.getEngine());
                        } else {
                            content.setVisibility(View.GONE);
                        }
                    }
                } else {
                    carLayout.setVisibility(View.GONE);
                    hintTv.setVisibility(View.VISIBLE);
                    hintTv.setText("请添加爱车");
                }
            }
        } else {
            carLayout.setVisibility(View.GONE);
            hintTv.setVisibility(View.VISIBLE);
            hintTv.setText("请登录");
        }
    }

    /**
     * 获取首页数据成功
     */
    @Override
    public void getHomePageInfoSuccess(HomePageInfoBean homePageInfoBean) {
        this.homePageInfoBean = homePageInfoBean;
        if (refreshLayout.isRefreshing()) {
            refreshLayout.setRefreshing(false);
        }
        if (homePageInfoBean != null) {
            if (homePageInfoBean.getProductCategory() != null) {
                adapter.updateData(homePageInfoBean.getProductCategory());
            }

            if (!StringUtil.isEmpty(homePageInfoBean.getCompanyDesc())) {
                webView.loadData(WebViewUtil.getHtmlData(homePageInfoBean.getCompanyDesc()), mimeType, null);
            }

            if (homePageInfoBean.getLoopLists() != null) {
                SharedPreferencesUtil.setStringParam(getContext(), SharedPreferencesKey.BANNER_DATA, gson.toJson(homePageInfoBean.getLoopLists()));
                setBannerView(homePageInfoBean.getLoopLists());
            }

            if (homePageInfoBean.getMycar() != null) {
                SharedPreferencesUtil.setStringParam(getContext(), SharedPreferencesKey.MY_CAR, gson.toJson(homePageInfoBean.getMycar()));
            }

            setCarLayoutView();
        }
    }

    /**
     * 获取首页数据失败
     */
    @Override
    public void getHomePageInfoFailed() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.setRefreshing(false);
        }
    }

    @OnClick({R.id.hint_tv, R.id.car_detail_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.hint_tv:
                if (hintTv.getText().toString().equals("请登录")) {
                    if (!UserInfoManager.getInstance().isLogin()) {
                        startActivity(new Intent(getContext(), LoginActivity.class));
                    }
                } else {
                    startActivity(new Intent(getContext(), MyCarDetailActivity.class));
                }

                break;
            case R.id.car_detail_tv:
                startActivity(new Intent(HomePageFragment.this.getContext(), MyCarDetailActivity.class));
                break;
        }
    }
}
